#!/usr/bin/env python
# -*- coding:utf-8 -*-


class HandleBase(object):
    'Handle基类'
    RESPONSE_STATUS = {
            'OK': '200 OK',
            'NOTFOUND': '404 NOTFOUND',
            'MOVED': '301 Moved Permanently',
            }

    def __init__(self, environ):
        '构造函数'
        import cgi
        from util import config

        self._environ = environ
        self._set_status('OK')

        self._view = {}
        self._view['domain'] = self._environ['HTTP_HOST']
        self._view['domain_static'] = config.CONFIG['website_static']

        self._header = {}
        self._header['Content-Type'] = 'text/html;charset=uft-8'

        self._form = cgi.FieldStorage(
                fp=environ['wsgi.input'],
                environ=environ)

    def _set_status(self, status):
        '修改http状态码'
        self._response_status = HandleBase.RESPONSE_STATUS[status]

    def _add_header(self, key, value):
        '添加http头信息'
        self._header[key] = value

    def get_response_status(self):
        '返回http响应代码'
        return self._response_status

    def get_header(self):
        '返回http报文头部'
        header = [(k, v) for k, v in self._header.items()]
        return header

    def is_action(self, str_act):
        '确定str_act是否一个合法action'
        str_func = 'action_' + str_act
        return str_func in dir(self)

    def render(self, action_called):
        '渲染模板'
        from jinja2 import Environment
        from jinja2.loaders import FileSystemLoader
        from util import config

        env_loader = FileSystemLoader(config.CONFIG['tmpl_path'])
        env = Environment(loader=env_loader, autoescape=True)
        tmpl_name = self.__class__.__name__
        tmpl_name += '_' + action_called
        tmpl_name += '.html'
        tmpl = env.get_template(tmpl_name)
        outstr = tmpl.render(self._view)

        return outstr
